package com.dripx;

import android.content.Context;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

public class Engine extends CordovaPlugin {
    private Context context = null;

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        context = this.cordova.getContext();
        switch (action) {
            case "test":
                String params = args.toString();
                callbackContext.success(params);
                break;
            case "infrared":
                int carrierFrequency = args.getInt(0);
                JSONArray list = args.getJSONArray(1);
                int index = 0;
                int length = list.length();
                int[] pattern = new int[length];
                while (index < length) {
                    pattern[index] = list.getInt(index);
                    index++;
                }
                this.transmitInfrared(carrierFrequency, pattern);
                JSONObject object = new JSONObject();
                object.put("carrierFrequency", carrierFrequency);
                object.put("pattern", pattern);
                callbackContext.success(object.toString());
                break;
            default:
                callbackContext.error("no action named '" + action + "'");
                return false;
        }
        return true;
    }

    private static HashMap<String, Service> map = new HashMap<>();

    /**
     * @param cls Class
     * @return Service
     */
    private Service getService(Class cls) {
        try {
            String clsnm = cls.getName();
            if (!map.containsKey(clsnm)) {
                Service service = (Service) cls.newInstance();
                service.setContext(this.context);
                map.put(clsnm, service);
                return service;
            } else {
                return map.get(clsnm);
            }
        } catch (Throwable throwable) {
            throw new DripException(throwable.getClass().getName() + ":" + throwable.getMessage());
        }
    }


    private void transmitInfrared(int carrierFrequency, int[] pattern) {
        ConsumerInfraredService service = (ConsumerInfraredService) getService(ConsumerInfraredService.class);
        service.transmit(carrierFrequency, pattern);
    }
}